<script>
import { onBeforeMount, onMounted, reactive, toRefs } from 'vue';
import { fileDelete, fileUpload } from '@/services';

export default {
  name: 'UploadPage',
  props: {
    saveFileArr: propTypes.array.def([]), // 保存的文件数组编号
    fileType: propTypes.string.def('image-card'), // 文件类型格式 image-card(照片墙)  image  text
    maxNum: propTypes.number.def(1), // 最大上传文件数
    listType: propTypes.array.def(['image/jpeg', 'image/png', 'image/gif']) // 文件形式  .doc,.docx,.pdf,.xls,.xlsx,.zip,.rar,.jpg,.png,.jpeg,.svg,.gif
  },
  setup(props) {
    const allData = reactive({
      fileList: [],
      maxNum: props.maxNum ? props.maxNum : 5
    });
    const emit = defineEmits(['update:saveFileArr']);
    const localSaveFileArr = ref([...props.saveFileArr]);
    // 文件上传和删除
    const changeFile = async file => {
      if (file.event) {
        // 文件上传
        const formdata = new FormData();
        formdata.append('files', file.file.file);
        const config = {
          headers: { 'Content-Type': 'multipart/form-data' }
        };
        const res = await fileUpload(formdata, config);
        if (res && res.code === 0) {
          if (res.list.length > 0) {
            const datas = res.list[0];
            // props.saveFileArr.push(datas);
            localSaveFileArr.value.push(datas);
            // 通过 emit 通知父组件更新数据
            emit('update:saveFileArr', [...localSaveFileArr.value]);
          }
        } else {
          allData.fileList = [];
          const param = {
            id: file.file.id,
            name: file.file.name,
            status: 'error'
          };
          allData.fileList.push(param);
        }
      } else {
        // 文件删除,根据文件名进行匹配
        let fileIndex = null;
        props.saveFileArr.map((item, index) => {
          if (file.file.name === item.fileOriginalName) {
            fileIndex = index;
          }
          return item;
        });
        const fileNos = [];
        fileNos.push(props.saveFileArr[fileIndex].fileNo);
        const res = await fileDelete(fileNos);
        if (res && res.code === 200) {
          localSaveFileArr.value.splice(fileIndex, 1);
          emit('update:saveFileArr', [...localSaveFileArr.value]);
        }
      }
    };
    onMounted(() => {
      // 修改时图片回显
      allData.fileList = [];
      if (props.saveFileArr.length > 0) {
        props.saveFileArr.map(item => {
          const params = {
            id: item.fileNo,
            name: item.fileOriginalName,
            status: 'finished',
            url: item.fileCloudStorageKey
          };
          allData.fileList.push(params);
          return item;
        });
      }
    });
    onBeforeMount(() => {
      allData.fileList = [];
    });
    return {
      ...toRefs(allData),
      changeFile,
      fileList
    };
  }
};
</script>

<template>
  <!-- 公共文件上传组件，包含图片、文件等 -->
  <div class="uploadPage">
    <NUpload
      v-if="listType == 'image-card'"
      v-model:file-list="fileList"
      :accept="fileType"
      :list-type="listType"
      :max="maxNum"
      show-download-button
      @change="changeFile"
    >
      上传文件
    </NUpload>
  </div>
</template>

<style lang="less">
.uploadPage {
  width: 100%;
}
</style>
